<template>
  <div class="news-container">
    <div class="news-template">
      <div class="news-template-main">
        <div class="news-template-box">
          <el-form
            :model="ruleForm"
            :rules="rules"
            ref="ruleForm"
            label-width="100px"
            class="demo-ruleForm"
          >
            <el-form-item label="模板名称" label-width="134px" prop="name">
              <el-input
                v-model="ruleForm.name"
                placeholder="请输入合同模板名称"
              ></el-input>
            </el-form-item>
            <el-form-item label="合同类型" label-width="134px" prop="type">
              <el-radio-group v-model="ruleForm.type">
                <el-radio label="2">适用个人类客户</el-radio>
                <el-radio label="3">适用公司类客户</el-radio>
                <el-radio label="1">通用类</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="适用范围" label-width="134px" prop="type">
              <el-radio-group v-model="ruleForm.range">
                <el-radio
                  v-for="item in scopelist"
                  :label="item.id"
                  :key="item.id"
                  >{{ item.value }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
            <!-- <el-form-item label="模板图标" label-width="134px" prop="iconList">
              <el-upload
                class="upload-demo"
                action="https://jsonplaceholder.typicode.com/posts/"
                :file-list="ruleForm.iconList"
                v-model="ruleForm.iconList"
                :on-change="handleChangeIcon"
                :on-remove="handleRemoveIcon"
                :auto-upload="false"
                >
                <el-button size="small"><i class="el-icon-upload2"></i>点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只支持.jpg 格式</div>
              </el-upload>
            </el-form-item> -->
            <el-form-item label="模板底稿" label-width="134px" prop="draftList">
              <el-upload
                class="upload-demo"
                action="https://jsonplaceholder.typicode.com/posts/"
                :file-list="ruleForm.draftList"
                v-model="ruleForm.draftList"
                :limit="1"
                :on-change="handleChangeDraft"
                :on-remove="handleRemoveDraft"
                :auto-upload="false"
                ref="upload"
                id="uploaddom"
              >
                <el-button size="small"
                  ><i class="el-icon-upload2"></i>点击上传</el-button
                >
                <div slot="tip" class="el-upload__tip">
                  支持扩展名：只支持.docx格式
                </div>
              </el-upload>
            </el-form-item>
            <el-form-item
              class="form-indate"
              label="模板有效期"
              label-width="134px"
              prop="type"
            >
              <el-radio-group
                v-model="ruleForm.datetype"
                @change="radioChecked"
              >
                <el-row type="flex" align="middle">
                  <el-radio label="固定日期"></el-radio>
                  <el-col class="form-indate-item">
                    <el-form-item prop="date1">
                      <el-date-picker
                        type="date"
                        placeholder="选择日期"
                        @change="handleTimeChange"
                        v-model="ruleForm.date1"
                        style="width: 100%"
                      ></el-date-picker>
                    </el-form-item>
                  </el-col>
                  <el-col class="line" :span="2">至</el-col>
                  <el-col class="form-indate-item">
                    <el-form-item prop="date2">
                      <el-date-picker
                        placeholder="选择时间"
                        @change="handleTimeChange"
                        v-model="ruleForm.date2"
                        style="width: 100%"
                      ></el-date-picker>
                    </el-form-item>
                  </el-col>
                </el-row>
                <!-- <el-row type="flex" align="middle">
                  <el-radio label="启用后"></el-radio>
                    <el-col class="form-indate-item">
                      <el-form-item prop="startdate" required>
                        <el-select v-model="ruleForm.startdate">
                          <el-option label="当天" value="当天"></el-option>
                          <el-option label="隔天" value="隔天"></el-option>
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col class="line line-2" :span="2">起生效，有效天数</el-col>
                    <el-col class="form-indate-item new-date">
                      <el-form-item prop="newdate">
                        <el-input v-model="ruleForm.newdate"></el-input>
                        <i class="unit-icon">天</i>
                      </el-form-item>
                    </el-col>
                </el-row> -->
              </el-radio-group>
            </el-form-item>
            <el-form-item label="合同描述" label-width="134px" prop="message">
              <el-input v-model="ruleForm.message"></el-input>
            </el-form-item>
            <el-form-item
              class="lv-input"
              label="优先级"
              label-width="134px"
              prop="message"
            >
              <el-select v-model="ruleForm.lv">
                <el-option label="1" value="1"></el-option>
                <el-option label="2" value="2"></el-option>
                <el-option label="3" value="3"></el-option>
                <el-option label="4" value="4"></el-option>
                <el-option label="5" value="5"></el-option>
                <el-option label="6" value="6"></el-option>
                <el-option label="7" value="7"></el-option>
                <el-option label="8" value="8"></el-option>
                <el-option label="9" value="3"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="启用/禁用" label-width="134px" prop="isUse">
              <el-radio-group v-model="ruleForm.isUse">
                <el-radio label="1">启用</el-radio>
                <el-radio label="2">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item class="news-template-btn">
              <el-button
                type="primary"
                size="small"
                @click="submitForm('ruleForm')"
                >下一步：设置模板规则参数</el-button
              >
              <el-button size="small" @click="backPage">返回</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
    <el-dialog
      :visible="dialogVisible"
      :show-close="true"
      :before-close="close"
      width="50%"
      title="文件预览"
    >
      <pdf :src="FeileSrc" v-for="i in numPages" :page="i" :key="i"></pdf>
    </el-dialog>
  </div>
</template>

<script>
import { getscopedataapi, viewdocx } from "@/api/contractTemplate.js";
import pdf from "vue-pdf";
import CMapReaderFactory from "vue-pdf/src/CMapReaderFactory.js";
export default {
  data() {
    return {
      dialogVisible: false,
      basestr: "",
      FeileSrc: "",
      numPages: 0,
      title: "新增模板",
      filename: "",
      filetype: "",
      isChecked: true,
      isclick: true,
      n: 10,
      ruleForm: {
        name: "", // 模板名字
        number: "", // 模板编号
        type: "2", // 合同类型
        fileName: [],
        range: null, // 适用范围
        iconList: [],
        draftList: [], // 文件上传列表
        message: "", // 合同描述
        lv: "1", // 优先级
        isUse: "1", // 模板状态
        datetype: "固定日期",
        date1: "", // 开始时间
        date2: "", // 结束时间
        startdate: "当天",
        newdate: "",
        file: "",
      },
      radio: 1,
      scopelist: [],
      rules: {
        name: [{ required: true, message: "请输入模板名称", trigger: "blur" }],
        number: [
          { required: true, message: "请输入模板编号", trigger: "blur" },
        ],
        type: [
          { required: true, message: "请选择合同类型", trigger: "change" },
        ],
        range: [
          { required: true, message: "请选择适用范围", trigger: "change" },
        ],
        iconList: [
          { required: true, message: "请选上传模板图标", trigger: "change" },
        ],
        draftList: [
          { required: true, message: "请选上传模板底稿", trigger: "change" },
        ],
        datetype: [
          { required: true, message: "请选择模板有效期", trigger: "change" },
        ],
        date1: [{ required: true, message: "请选择时间", trigger: "change" }],
        date2: [{ required: true, message: "请选择时间", trigger: "change" }],
        startdate: [
          { required: true, message: "请选择时间", trigger: "change" },
        ],
        newdate: [{ required: false, message: "请输入天数", trigger: "blur" }],
      }, // 校验规则
      updateFile: "", // base64文件
      fileName: "", // 文件名
    };
  },
  components: {
    pdf,
  },
  methods: {
    getscopedata() {
      getscopedataapi({
        transId: "06234019",
        accessHost: "20101",
        cifSeq: "300000454",
      }).then((res) => {
        if (res.data.code === "000000") {
          this.scopelist = res.data.data.list;
        }
      });
    },
    submitForm(formName) {
      // 获取页面数据进行缓存并跳转下一步
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 表单校验成功
          // 时间转换 YY-MM-DD
          let stTime = this.ruleForm.date1;
          let endTime = this.ruleForm.date2;
          if (typeof this.ruleForm.date1 !== "string") {
            let month = this.ruleForm.date1.getMonth() + 1;
            if (month < 10) {
              month = "0" + month;
            }
            let newDate = this.ruleForm.date1.getDate();
            if (newDate < 10) {
              newDate = "0" + newDate;
            }
            stTime =
              this.ruleForm.date1.getFullYear() + "-" + month + "-" + newDate;
          }
          if (typeof this.ruleForm.date2 !== "string") {
            let month2 = this.ruleForm.date2.getMonth() + 1;
            if (month2 < 10) {
              month2 = "0" + month2;
            }
            let newDate2 = this.ruleForm.date2.getDate();
            if (newDate2 < 10) {
              newDate2 = "0" + newDate2;
            }
            endTime =
              this.ruleForm.date2.getFullYear() + "-" + month2 + "-" + newDate2;
          }
          // 保存数据
          const data = {
            templateName: this.ruleForm.name.trim(),
            typeId: parseInt(this.ruleForm.type),
            scopeId: parseInt(this.ruleForm.range),
            fileName: this.fileName,
            baseStr: this.updateFile,
            startDate: stTime,
            endDate: endTime,
            details: this.ruleForm.message.trim(),
            contractLevel: parseInt(this.ruleForm.lv),
            enable: parseInt(this.ruleForm.isUse),
            draftList: this.ruleForm.draftList,
            namefile: this.filename,
            typefile: this.filetype,
          };
          window.localStorage.setItem("setData", JSON.stringify(data));
          this.$router.push({
            name: "templateParam",
          });
        } else {
          return false;
        }
      });
    },
    close() {
      this.dialogVisible = false;
    },
    backPage() {
      // 取消操作 清除缓存
      window.localStorage.removeItem("setData");
      window.localStorage.removeItem("templateDate");
      this.$router.push({
        name: "templateList",
      });
    },
    radioChecked(val) {
      // 时间类型选择
      if (val === "固定日期") {
        this.rules.date1[0].required = true;
        this.rules.date2[0].required = true;
        this.rules.startdate[0].required = false;
        this.rules.newdate[0].required = false;
      } else if (val === "启用后") {
        this.rules.date1[0].required = false;
        this.rules.date2[0].required = false;
        this.rules.startdate[0].required = true;
        this.rules.newdate[0].required = true;
      }
    },
    handleRemoveIcon(file, fileList) {
      this.ruleForm.iconList = fileList;
    },
    handleChangeIcon(file, fileList) {
      this.ruleForm.iconList = fileList;
    },
    handleRemoveDraft(file, fileList) {
      // 删除文件触发
      const span = document.getElementsByClassName("viewdecx")[0];
      span.remove();
      this.ruleForm.draftList = fileList;
      this.fileName = "";
      this.updateFile = "";
    },
    handleChangeDraft(file, fileList) {
      // 上传文件列表发生改变
      const type1 = file.name.substring(file.name.lastIndexOf(".") + 1);
      this.ruleForm.draftList = fileList;
      if (type1 !== "docx") {
        this.$message({
          message: "上传文件只支持.docx格式!",
          type: "error",
        });
        this.ruleForm.draftList = [];
      } else {
        const newFile = file.raw;
        this.getBase64File(newFile).then((res) => {
          const params = res.split(";base64,");
          this.basestr = params[1];
          this.updateFile = params[1];
        });
        const span = document.createElement("span");
        span.className = "viewdecx";
        span.innerHTML = '<i class="el-icon-view"></i>预览docx';
        span.style.color = "#409EFF";
        span.style.cursor = "pointer";
        span.style.marginLeft = "10px";
        span.onclick = this.viewdoc;
        document.getElementById("uploaddom").appendChild(span);
      }
      this.fileName = file.name.split(".")[0];
    },
    viewdoc() {
      if (this.isclick) {
        this.isclick = false;
        const viewBtn = document.getElementsByClassName("viewdecx")[0];
        const b = document.createElement("b");
        b.style.color = "#999";
        b.style.margin = "0px 15px";
        b.style.fontWeight = "normal";
        viewBtn.style.color = "#ccc";
        viewBtn.style.cursor = "default";
        const timer = setInterval(() => {
          const index = this.n--;
          b.innerHTML = `(${index}s)`;
          if (index <= 0) {
            this.n = 10;
            b.remove();
            viewBtn.style.color = "#409EFF";
            viewBtn.style.cursor = "pointer";
            clearInterval(timer);
            this.isclick = true;
          }
        }, 1000);
        document.getElementById("uploaddom").appendChild(b);
        viewdocx({
          transId: "06135009",
          accessHost: "1111",
          baseStr: this.basestr,
        }).then((res) => {
          if (res.data.code === "000000") {
            this.dialogVisible = true;
            this.ShowFile(res.data.data.baseStr);
          }
        });
      } else {
        this.$message({
          type: "error",
          message: `请${this.n}秒后重新点击预览`,
        });
      }
    },
    getBase64File(file) {
      //  文件base64转换
      return new Promise(function (resolve, reject) {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        let updateFile = "";
        reader.onload = () => {
          updateFile = reader.result;
        };
        reader.onerror = (error) => {
          reject(error);
        };
        reader.onloadend = () => {
          resolve(updateFile);
        };
      });
    },
    handleTimeChange() {
      // 填写时间校验
      if (this.ruleForm.date1 !== "" && this.ruleForm.date2 !== "") {
        const date1 = new Date(this.ruleForm.date1).getTime();
        const date2 = new Date(this.ruleForm.date2).getTime();
        if (date1 > date2) {
          this.$message({
            message: "到期时间不得早于起始时间",
            type: "error",
          });
          this.ruleForm.date2 = "";
        }
      }
    },
    ShowFile(base) {
      const datas = "data:application/pdf;base64," + base;
      this.FeileSrc = pdf.createLoadingTask({ url: datas, CMapReaderFactory });
      this.FeileSrc.promise.then((pdf) => {
        this.numPages = pdf.numPages;
      });
    },
  },
  created() {
    // 清理缓存
    window.localStorage.removeItem("templateDate");
  },
  mounted() {
    this.ruleForm.range = this.radio;
    if (this.$route.query.back === "back") {
      const data = JSON.parse(window.localStorage.getItem("setData"));
      if (data) {
        const {
          templateName,
          typeId,
          scopeId,
          fileName,
          startDate,
          endDate,
          details,
          contractLevel,
          enable,
          draftList,
        } = data;
        const filnaeobj = [
          {
            name: fileName,
          },
        ];
        this.ruleForm = {
          fileName: filnaeobj,
          name: templateName, // 模板编号
          type: `${typeId}`, // 合同类型
          range: scopeId, // 适用范围
          message: details, // 合同描述
          lv: contractLevel, // 优先级
          isUse: `${enable}`, // 模板状态
          date1: startDate, // 开始时间
          date2: endDate, // 结束时间
          draftList: draftList,
        };
        this.updateFile = data.baseStr;
        this.basestr = data.baseStr;
        this.fileName = fileName;
        if (draftList) {
          const span = document.createElement("span");
          span.className = "viewdecx";
          span.innerHTML = '<i class="el-icon-view"></i>预览docx';
          span.style.color = "#409EFF";
          span.style.cursor = "pointer";
          span.style.marginLeft = "10px";
          span.onclick = this.viewdoc;
          document.getElementById("uploaddom").appendChild(span);
        }
        this.getscopedata();
        return false;
      }
    } else {
      window.localStorage.removeItem("setData");
    }
    this.getscopedata();
  },
};
</script>

<style scoped>
.news-template {
  width: 100%;
  min-height: 100%;
  background: #fff;
}
.news-template-title {
  height: 64px;
  margin-bottom: 20px;
}
.news-template-title i {
  width: 4px;
  height: 16px;
  background: #5290ff;
  display: inline-block;
  margin-right: 10px;
  vertical-align: middle;
}
.news-template-title h3 {
  margin: 0 26px;
  padding-left: 3px;
  font-size: 14px;
  line-height: 64px;
  font-weight: bold;
  border-bottom: 1px solid rgba(187, 187, 187, 0.43);
}
.news-template-box {
  margin: 0 26px;
  padding: 40px 0 80px 0;
}
.news-template-box >>> .el-form-item__label {
  text-align: left;
  line-height: 36px;
}
.news-template-box >>> .el-form-item {
  margin-bottom: 15px;
  height: 36px;
}
.news-template-box >>> .el-input__inner {
  height: 30px;
  font-size: 14px;
  width: 496px;
}
.news-template-box >>> .el-form-item__content {
  line-height: 36px;
}
.news-template-box >>> .el-form-item__error {
  padding-top: 2px;
}
.upload-demo {
  display: flex;
  height: 36px;
  line-height: 36px;
  align-items: center;
}
.number {
  display: inline-block !important;
  margin: 0 10px !important;
  color: #f00 !important;
}
.upload-demo i {
  margin-right: 6px;
}
.upload-demo >>> .el-upload__tip {
  margin-top: 0;
  margin-left: 10px;
  margin-right: 20px;
}
.upload-demo >>> .el-upload-list {
  display: flex;
  align-items: center;
}
.upload-demo >>> .el-upload-list__item {
  margin: 0;
}
.news-template-box .form-indate {
  height: auto;
}
.form-indate >>> .el-form-item__content {
  margin: 0;
}
.form-indate >>> .el-radio-group {
  display: flex;
  flex-direction: column;
}
.form-indate >>> .form-indate-item {
  height: 36px;
  width: 180px;
}
.form-indate >>> .form-indate-item .el-date-editor {
  width: 180px;
}
.form-indate >>> .form-indate-item .el-input__inner {
  width: 180px;
}
.form-indate >>> .line {
  font-size: 14px;
  width: 40px;
  text-align: center;
}
.form-indate >>> .el-radio {
  width: 95px;
  margin: 0;
}
.form-indate >>> .line-2 {
  width: 113px;
  margin: 0 6px;
}
.form-indate >>> .new-date {
  position: relative;
  width: 94px;
}
.form-indate >>> .new-date .el-input__inner {
  width: 94px;
  padding-right: 24px;
}
.form-indate >>> .new-date .unit-icon {
  position: absolute;
  right: 6px;
  font-style: normal;
}
.form-indate >>> .el-row {
  margin-bottom: 15px;
}
.news-template-btn >>> .el-form-item__content {
  margin: 40px 0 0 185px !important;
}
.news-template-btn >>> .el-button--primary {
  margin-right: 90px;
}
.news-template-box .lv-input >>> .el-input__inner {
  width: 100px;
}
</style>
